﻿using System;
using System.Windows.Forms;

namespace TimeTools {
    public partial class StopWatchControl : UserControl {
        private bool _isRunning;
        private DateTime _start;
        private DateTime _stop;
        private TimeSpan _storedTime = new TimeSpan(0);

        public StopWatchControl() {
            InitializeComponent();
        }

        private void _startStop_Click(object sender, EventArgs e) {
            if (_isRunning) {
                StopTimer();
            } else {
                StartTimer();
            }
        }

        private void _refreshTimer_Tick(object sender, EventArgs e) {
            TimeSpan t = _storedTime + (DateTime.Now - _start);
            _timer.Text = TimeFormatHelpers.FormatTimeSpan(t);
        }

        private void AddEvent(DateTime eventTime, TimeSpan timeSpan, string message) {
            string str = string.Format("{0} -- {1} -- {2}", TimeFormatHelpers.FormatDateTime(eventTime), TimeFormatHelpers.FormatTimeSpan(timeSpan), message);
            int index = _events.Items.Add(str);
            _events.SetSelected(index, true);
        }

        private void _reset_Click(object sender, EventArgs e) {
            StopTimer();
            _storedTime = new TimeSpan(0);
            _startTime.Text = "0000-00-00 00:00:00.000";
            _stopTime.Text = "0000-00-00 00:00:00.000";
            _timer.Text = "00.00:00:00.000";
            AddEvent(DateTime.Now, _storedTime, "Timer reset");
        }

        private void StartTimer() {
            _start = DateTime.Now;
            _startTime.Text = TimeFormatHelpers.FormatDateTime(_start);
            _stopTime.Text = "0000-00-00 00:00:00.000";
            _startStop.Text = "Stop";
            if (!_isRunning) {
                AddEvent(_start, _storedTime, "Timer started");
            }
            _refreshTimer.Enabled = true;
            _isRunning = true;
        }

        private void StopTimer() {
            _refreshTimer.Enabled = false;
            _stop = DateTime.Now;
            _stopTime.Text = TimeFormatHelpers.FormatDateTime(_stop);
            _startStop.Text = "Start";
            TimeSpan timeSpan = DateTime.Now - _start;
            _timer.Text = TimeFormatHelpers.FormatTimeSpan(_storedTime + timeSpan);
            _storedTime += timeSpan;
            if (_isRunning) {
                AddEvent(_stop, _storedTime, "Timer stopped");
            }
            _isRunning = false;
        }
    }
}
